import {getDicts} from "@/api/system/dict/data.js";

/**
 * 维护字典数据缓存, 不用每次查字典都要到服务端查询
 * dict
 */
const useDictStore = defineStore(
        'dict',
        {
            state: () => ({
                dicts: []
            }),
            actions: {
                // 设置字典
                setDict(_key, value) {
                    if (_key !== null && _key !== "") {
                        this.dicts.push({
                            key: _key,
                            value: value
                        });
                    }
                },
                // 获取字典
                getDict(_key) {
                    if (_key == null && _key === "") {
                        return null;
                    }
                    let dict = this.dicts.find(_dict => _dict['key'] === _key);
                    return dict?.value ?? null;
                },
                // 删除字典
                removeDict(_key) {
                    let bln = false;
                    let index = this.dicts.findIndex(_dict => _dict['key'] === _key);
                    if (index > -1) {
                        this.dicts.splice(index, 1);
                        bln = true;
                    }
                    return bln;
                },
                // 清空字典
                cleanDict() {
                    this.$reset()
                },
                // 初始字典
                async initDict() {
                    const res = await getDicts()
                    if (res.data != null ){
                        this.dicts = res.data;
                    }
                    return res
                }
            }
        })

export default useDictStore
